﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using System.Web.Configuration;
using System.Net;
using ClassLibrary.DAO;
using ClassLibrary.Data;
using ClassLibrary.Entity;
using System.Collections.Generic;

public partial class UserControl_ucSuccessful : System.Web.UI.UserControl
{
    string authToken, txToken, query;
    string strResponse;
    TblEmailDAO emailDAO = new TblEmailDAO(Global.CONNECTION_STRING);
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if ((Session[Global.SESSION_TOTAL] == null) || (Session[Global.SESSION_CART] == null))
            {
                Response.Redirect("~/Index.aspx");
            }
            else
            {
               
                authToken = WebConfigurationManager.AppSettings["PDTToken"];
                //read in txn token from querystring
                txToken = Request.QueryString.Get("tx");
                query = string.Format("cmd=_notify-synch&tx={0}&at={1}",
                                      txToken, authToken);
                // Create the request back
                string url = WebConfigurationManager.AppSettings["PayPalSubmitUrl"];
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);

                // Set values for the request back
                req.Method = "POST";
                req.ContentType = "application/x-www-form-urlencoded";
                req.ContentLength = query.Length;

                // Write the request back IPN strings
                StreamWriter stOut = new StreamWriter(req.GetRequestStream(),
                                         System.Text.Encoding.ASCII);
                stOut.Write(query);
                stOut.Close();

                // Do the request to PayPal and get the response
                StreamReader stIn = new StreamReader(req.GetResponse().GetResponseStream());
                strResponse = stIn.ReadToEnd();
                stIn.Close();

                // sanity check
                // Label2.Text = "<pre>" + strResponse + "</pre>";
                Label2.Text = "Thank you very much for your order product from Push mail. Please mail below for your order details.</br> " +
                                 "If you are not redirected within 10 seconds.";
                // If response was SUCCESS, parse response string and output details
                if (strResponse.StartsWith("SUCCESS"))
                {

                    PDTHolder pdt = PDTHolder.Parse(strResponse);
                    Label1.Text =
                    string.Format("Thank you {0} {1} [{2}] for your payment of {3} {4}!",
                    pdt.PayerFirstName, pdt.PayerLastName,
                    pdt.PayerEmail, pdt.GrossTotal, pdt.Currency);

                    //  insert order :

                    #region insert booking
                    try
                    {
                        
                        TblBookingDAO bookingDAO = new TblBookingDAO(Global.CONNECTION_STRING);
                        TblBooking booking = new TblBooking();

                        if (Session[Global.SESSION_BOOK] == null)
                        {
                            booking = new TblBooking();
                        }
                        else
                        {
                            booking = (TblBooking)Session[Global.SESSION_BOOK];
                        }

                        TblCustomers userAccount = (TblCustomers)Session[Global.SESSION_LOGGED_USER];
                        booking.Customer = userAccount;
                        booking.CusID = userAccount.CusID;

                        booking.DateBook = DateTime.Now;
                        booking.DateActive = DateTime.Now;
                        booking.Status = 1;
                        booking.PaymentMethod = 2;// 2 By paypal
                        // order.Total = float.Parse(Session[Global.SESSION_TOTAL].ToString());

                        booking.TotalPrice = Decimal.Parse(Session[Global.SESSION_TOTAL].ToString());

                        List<TblBookingDetail> arrItems = (List<TblBookingDetail>)Session[Global.SESSION_CART];
                        int id;

                        bookingDAO.Insert(booking, arrItems, out id);

                        //emailDAO.UpStatus(

                        foreach (TblBookingDetail order in arrItems)
                        {
                            emailDAO.UpStatus(order.IDEmail);
                        }


                        Session[Global.SESSION_CART] = null;
                        Session[Global.SESSION_TOTAL] = null;

                    }
                   catch (Exception ex)
                   {
                       Session[Global.SESSION_ERROR] = ex;
                       Response.Redirect(Global.ERROR_PAGE, true);
                   }
                  
                    #endregion
                }
                else
                {
                    Label1.Text = "Oooops, something went wrong...";
                }
            }
        }
    }
    protected void timer_Tick(object sender, EventArgs e)
    {
        Response.Redirect("~/Index.aspx");
    }
}
